package com.sikaryofficial.backend.service.points;

import cn.hutool.core.text.CharSequenceUtil;
import com.sikaryofficial.backend.manager.ProductStaticsManager;
import com.sikaryofficial.backend.service.IPointsDetailStrategy;
import com.sikaryofficial.common.core.constant.PointRuleConstant;
import com.sikaryofficial.system.api.RemoteQrCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author : qinjinyuan
 * @desc : 扫描评价积分服务
 * @date : 2023/10/31 18:58
 */
@Service(value = PointRuleConstant.SCAN_CODE + IPointsDetailStrategy.SUFFIX)
@Slf4j
public class ScanCodePointsService extends AbstractPointService {
    @Autowired
    private RemoteQrCodeService remoteQrCodeService;
    @Autowired
    private ProductStaticsManager productStaticsManager;
    /**
     * 更新积分明细数据
     *
     * @param sourceId
     * @param userId
     * @param pointsDetailValue
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public boolean updatePointsByInputValue(Long sourceId, Long userId, Integer pointsDetailValue, String param, String sourceName) {
        boolean isOver = checkEnable(PointRuleConstant.SCAN_CODE);
        // 未登录不获取积分
        if (Objects.isNull(userId) || Objects.equals(userId, 0L)) {
            return false;
        }
        if (isOver) {
            log.info("SCAN_REGISTER 被禁用");
            return false;
        }
        if (CharSequenceUtil.isBlank(param)) {
            log.info("param is null");
            return false;
        }
        if (Boolean.FALSE.equals(remoteQrCodeService.existProductQrCode(param).getData())) {
            log.info("扫码商品部存在");
            return false;
        }
        // 判定是否被扫码
        if (Boolean.FALSE.equals(remoteQrCodeService.verifyScanCode(param).getData())) {
            // 扫码统计 | 详情记录 | 统计缓存更新
            productStaticsManager.updateStatisticsAndCache(param);
            // 更新二维码被扫信息
            remoteQrCodeService.updateProductQrData(param);
            // 一支烟获取一次奖励
            this.increasePoints(sourceId, userId, PointRuleConstant.SCAN_CODE, sourceName);
        } else {
            log.info("扫码商品已被扫码");
        }
        return false;
    }
}
